---
import { Avatar, Breadcrumbs, BreadcrumbsItem, Heading } from 'accessible-astro-components'
import { Image } from 'astro:assets'
import sanitizeHtml from 'sanitize-html'

/**
 * PageHeader Component
 *
 * @description PageHeader description
 */
interface Props {
  /**
   * Additional classes to apply to the PageHeader
   */
  class?: string
  /**
   * The featured image of the page
   */
  featuredImage?: string
  /**
   * The title of the page
   */
  title: string
  /**
   * The subtitle of the page
   * @description Can contain HTML content (will be sanitized)
   */
  subtitle?: string
  /**
   * The background color of the page header
   * @type {'primary' | 'secondary' | 'neutral' | 'gradient' | 'bordered' | undefined}
   * @default undefined - Uses the default background color
   */
  /**
   * The author of the page
   */
  author?: {
    name: string
    image: string
    bio: string
  }
  bgType?: 'primary' | 'secondary' | 'neutral' | 'gradient' | 'bordered'
  /**
   * Whether to show the breadcrumbs
   */
  showBreadcrumbs?: boolean
  /**
   * Custom breadcrumb labels to override the default URL-based labels
   * @description Object mapping URL segments to their display labels
   */
  customBreadcrumbLabels?: Record<string, string>

  /**
   * Whether to join the last breadcrumb
   */
  joinLastBreadcrumb?: boolean
}

const {
  class: className,
  title,
  subtitle,
  bgType,
  showBreadcrumbs = true,
  featuredImage,
  author,
  customBreadcrumbLabels,
  joinLastBreadcrumb = false,
} = Astro.props

// Helper function to format segment names
const formatSegment = (segment: string): string => {
  if (customBreadcrumbLabels?.[segment]) {
    return customBreadcrumbLabels[segment]
  }
  return segment
    .split('-')
    .map((word) => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ')
}

// Sanitize subtitle HTML if present
const sanitizedSubtitle: string = subtitle
  ? sanitizeHtml(subtitle, {
      allowedTags: ['b', 'i', 'em', 'strong', 'a', 'span', 'br'],
      allowedAttributes: {
        a: ['href', 'title', 'target', 'rel'],
        span: ['class'],
      },
    })
  : ''
---

<section class:list={[className, 'page-header']}>
  <div class="container my-3">
    {
      showBreadcrumbs &&
        (() => {
          const path = Astro.url.pathname
          const segments = path.split('/').filter(Boolean)

          if (segments.length === 0) {
            return null
          }

          return (
            <Breadcrumbs>
              <BreadcrumbsItem href="/" label="Home" />
              {segments.map((segment, index) => {
                if (joinLastBreadcrumb && index === segments.length - 1) {
                  return null
                }

                const url = `/${segments.slice(0, index + 1).join('/')}`
                const isLast = index === segments.length - 1 || (joinLastBreadcrumb && index === segments.length - 2)

                const formattedName = (() => {
                  if (joinLastBreadcrumb && isLast) {
                    const prevSegment = segments[segments.length - 2]
                    const lastSegment = segments[segments.length - 1]
                    return `${formatSegment(prevSegment)}: ${formatSegment(lastSegment)}`
                  }

                  return formatSegment(segment)
                })()

                return <BreadcrumbsItem href={isLast ? undefined : url} label={formattedName} currentPage={isLast} />
              })}
            </Breadcrumbs>
          )
        })()
    }
  </div>
  <div class:list={['py-16', bgType && `bg-${bgType}`]}>
    <div class="space-content container">
      {
        featuredImage && (
          <div class="featured-image-container mb-8">
            <Image
              src={featuredImage}
              alt=""
              width={1200}
              height={250}
              class="h-[250px] w-full rounded-lg object-cover"
            />
          </div>
        )
      }
      <Heading level="h1">{title}</Heading>
      {sanitizedSubtitle && <p class="text-2xl" set:html={sanitizedSubtitle} />}
      {
        author && (
          <div class="mt-6 flex items-center">
            <Avatar title={author.name} image={author.image} subtitle={author.bio} />
          </div>
        )
      }
    </div>
  </div>
</section>

<style>
  .page-header {
    .bg-primary {
      background-color: light-dark(var(--color-primary-100), var(--color-primary-500));
    }

    .bg-secondary {
      background-color: light-dark(var(--color-secondary-100), var(--color-secondary-500));
    }

    .bg-neutral {
      background-color: light-dark(var(--color-neutral-300), var(--color-neutral-800));
    }

    .bg-gradient {
      background-image: linear-gradient(
        315deg,
        light-dark(var(--color-primary-100), var(--color-secondary-100)) 25%,
        light-dark(var(--color-secondary-100), var(--color-primary-200))
      );
      color: var(--color-neutral-900);
    }

    .bg-bordered {
      border: 1px solid var(--border-color-subtle);
      border-inline: 0;
    }

    .featured-image-container {
      max-height: 500px;
      overflow: hidden;
    }
  }
</style>
